var config = require("../../config");
var render_data = [];
var AppID = "wxd098bf5dc78dd5db", AppSecret = "700c90a873db94bcc1e0f5ed0c0dde0e";

var app = getApp();
Page({
  data: {
    total: 0,
    sum: 0,
    num: 0,
    phoneModelValue: [0, 0],
    silde:""
  },
  onLoad() {
    var _this = this;

    // 获取轮播
    wx.request({
      method: "POST",                                                                                                                            
      url: config.service.Silde,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
       if(res.data.code == 1){
         _this.setData({
           silde:res.data.data
         });
       }else{
         wx.showToast({
           title: res.data.msg,
           icon: 'loading',
           duration: 2000,
           mask: true
         });
       }
      }
    });
  
    wx.getSystemInfo({    //获取手机品牌和型号
      success: function (phone) {
        var brand = phone.brand, model = phone.model;
        wx.request({
          method: "POST",
          url: config.service.login,
          data: {
            open_id: wx.getStorageSync("userInfo").nickName,
            headicon: wx.getStorageSync("userInfo").avatarUrl,
            user_nickname: wx.getStorageSync("userInfo").nickName
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success(res) {
            console.log("登录:",res);
            if (res.data.code == 1) {
              wx.setStorageSync("loginInfo", res.data.data);
              faultClassifiCation(_this, brand, model);
            } 
          }
        });
      },
    });
  },
  onShareAppMessage(){

  },
  content() {
    this.setData({
      showMapDetails: false
    });
  },
  
  /**点击更换机型**/
  cpModel() {
   
    var _this = this;
    wx.getNetworkType({
      success: function (res) {
        if (res.networkType != "none") {
          wx.request({
            method: "POST",
            url: config.service.PhoneModel,
            data: {
              uid: wx.getStorageSync("loginInfo").uid,
              logintoken: wx.getStorageSync("loginInfo").token
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success(res) {
              console.log(res);
              if (res.data.code == 1) {
                _this.data.phoneInfo.brand_model = res.data.data;    //手机品牌和型号
                _this.setData({
                  phoneInfo: _this.data.phoneInfo,
                  CPF: "CPF"
                });
                
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'loading',
                  duration: 2000,
                  mask: true
                });
              }
            }
          });
        }
      },
    });
  },

  /**picker-view(滑动更换手机、手机型号)**/
  phoneBrandModel(e) {
    let td = this.data, phone = e.detail.value[0], model = e.detail.value[1];
    td.phoneInfo.ShowModel = phone;
    td.phoneInfo.value = [phone, phone == td.phoneInfo.value[0] ? model : 0];   //重新初始化picker-view的value数组数据
    this.setData({
      phoneInfo: td.phoneInfo,
      phoneModelValue: [phone, model]
    });
  },

  /**点击确定更换手机品牌**/
  spModel() {
    let _this = this, 
    brand = this.data.phoneInfo.brand_model[this.data.phoneModelValue[0]].brand_name, 
    model = this.data.phoneInfo.brand_model[this.data.phoneModelValue[0]].category[this.data.phoneModelValue[1]].category_name;
    faultClassifiCation(_this, brand, model);
    render_data = [];
    this.setData({
      CPF: '',
      num: 0,
      sum: 0,
      phoneModelValue: [0, 0]
    });
    wx.reportAnalytics('update_mobile', {
      'record_number': 1,
      'model': brand + model
    });
  },

  /**选择手机故障**/
  Module(e) {    
    let td = this.data, faultClassifiCation_item = e.currentTarget.dataset.index;
    let faultClassifiCation_id = td.phoneInfo.faultClassifiCationData[faultClassifiCation_item].id;
    let title = td.phoneInfo.faultClassifiCationData[faultClassifiCation_item].error_name;

    if(!td.phoneInfo.faultClassifiCationData[faultClassifiCation_item].select){
      this.setData({
        phoneInfo: td.phoneInfo,
        faultClassifiCation_item
      });
      faultList(this, td.phoneInfo.phoneModel_id, faultClassifiCation_id, title);
    }
    wx.reportAnalytics('fault_type',{
      'mobile': td.phoneInfo.phone_name,
      'mobile_fault_type': title
    });
  },

  /**查看手机故障详情**/
  map() {
    
    if (this.data.num > 0) {
      this.setData({
        showMapDetails: !this.data.showMapDetails
      });
    }
  
  },
  MapDetails(){
    if (this.data.num > 0) {
      this.setData({
        showMapDetails: !this.data.showMapDetails
      });
    }
  },
  remove(e) {
    let td = this.data,
    index = e.currentTarget.dataset.index, 
    price = parseInt(render_data[index].error_price), val = 0;
    for (var i = 0; i < render_data.length; i++) {
      if (render_data[index].item == render_data[i].item) {
        val++;
      }
    }
    if (val == 1) {
      td.phoneInfo.faultClassifiCationData[render_data[index].item].select = false;
      wx.reportAnalytics('cancel_fault', {
        'model': td.phoneInfo.phone_name,
        'fault': td.phoneInfo.faultClassifiCationData[render_data[index].item].error_name
      });
    }
    render_data.splice(index, 1);
    this.setData({
      render_data,
      sum: td.sum - price,
      num: td.num - 1,
      showMapDetails: render_data.length == 0 ? false : true,
      phoneInfo: td.phoneInfo
    });
  },

  /**指定故障报修列表的 “项” （faultList） **/
  itemsEvent(e) {
    let item = e.currentTarget.dataset.item;
    this.data.Ofault.faultListData[item].select = !this.data.Ofault.faultListData[item].select;
    this.setData({
      Ofault: this.data.Ofault,
      items: item
    });
  },

  /**指定故障报修列表的 “取消” （faultList） **/
  cancelEvent() {
    let td = this.data;
    td.Ofault.hintOfault = "";
    td.phoneInfo.faultClassifiCationData[td.faultClassifiCation_item].select = false;
    console.log(td.phoneInfo.faultClassifiCationData);
    this.setData({
      Ofault: td.Ofault,
      phoneInfo: td.phoneInfo
    });
  },

  /**指定故障报修列表的 “确定” （faultDetails） **/
  confirmEvent() {
    let td = this.data, status = 0;
    td.phoneInfo.faultClassifiCationData[td.faultClassifiCation_item].select = true;
    for (var i = 0; i < td.Ofault.faultListData.length; i++) {
      if (td.Ofault.faultListData[i].select == true) {
        status++;
        render_data.push(td.Ofault.faultListData[i]);
        td.Ofault.faultListData[i].item = td.faultClassifiCation_item;
        td.sum += parseInt(td.Ofault.faultListData[i].error_price);
        td.num++;
      }
    }
    if (status == 0) {
      wx.showToast({
        title: '请选择维修故障',
        icon: "loading",
        duration: 2000,
        mask: true
      });
    } else {
      td.Ofault.hintOfault = '';
      console.log(td.Ofault.title);
      wx.reportAnalytics('fault_type_sl', {
        'model': td.phoneInfo.phone_name,
        'fault': td.Ofault.title
      });
      this.setData({
        phoneInfo: td.phoneInfo,
        Ofault: td.Ofault,
        render_data,
        sum: td.sum,
        num: td.num,
      });
    }

  },

  /**立即预约**/
  book() {
    wx.reportAnalytics('make', {
      make_nums:1
    });
    
    if (this.data.num == 0 || this.data.num == undefined) {
      this.setData({
        NPfault: {    //未选择手机故障摸版数据
          hint_NPfault: "hint-NPfault",
          info: "请选择故障",
          buttonEvent: "NPfaultButton"
        }
      });
    } else {
      wx.navigateTo({
        url: '../MaintaiinScheme/MaintaiinScheme?data=' + JSON.stringify(render_data) + '&totalPrices=' + 
        this.data.sum + '&phoneModelId=' + this.data.phoneInfo.phoneModel_id+ '&phoneColor=' + this.data.phoneInfo.phoneColor,
        success: function (res) { }
      })
    }
  },

  /**确定、退出（未选择手机故障摸版）**/
  NPfaultButton() {
    this.setData({
      NPfault: {
        hint_NPfault: ""
      }
    });
  },
  contact(){
    wx.reportAnalytics('online_cs', {
      'nums': 1
    }); 
  },
  mobile(e) {
    wx.reportAnalytics('mobile_cs', {
      'nums': 1
    });
    wx.makePhoneCall({
      phoneNumber: '400-118-1234',
      success: function () {
        console.log("拨打电话成功！");
        app.aldstat.sendEvent('咨询', { '咨询类型': "电话客服" });
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    });
  },
  myOrder(){
    wx.reportAnalytics('my_order', {
      'look_over_nums': 1
    });
  }
});

/**总价**/
function totalPrices(obj) {
  for (var i = 0; i < obj.data.length; i++) {
    if (obj.data[i].select == true) {
      render_data.push(obj.data[i]);
    }
  }
  obj._this.setData({
    render_data
  });
}

/**故障分类**/
function faultClassifiCation(e, brand, model) {
 wx.getNetworkType({
   success: function(res) {
     if(res.networkType != "none"){
       wx.showLoading({
         title: '加载中...',
         mask: true
       });
       wx.request({
         method: "POST",
         url: config.service.faultModel,
         data: {
           uid: wx.getStorageSync("loginInfo").uid,
           logintoken: wx.getStorageSync("loginInfo").token,
           category: model
         },
         header: {
           'content-type': 'application/x-www-form-urlencoded'
         },
         success(res) {
           console.log("故障分类:", res);
           wx.hideLoading();
           if (res.data.code == 1) {
             e.setData({
               phoneInfo: {    //手机、手机型号
                 ShowModel: 0,
                 prickerEvent: "phoneBrandModel",
                 spModelEvent: 'spModel',
                 value: [0, 0],
                 img: res.data.data.category.thumb,
                 faultClassifiCationData: res.data.data.error_type,
                 mobileName: res.data.data.category,
                //  phone_name: res.data.data.category.brand_name + ' ' + res.data.data.category.category_name,
                 phone_name: res.data.data.category.brand_name + ' ' + res.data.data.category.mobile_name,
                 phoneModel_id: res.data.data.category.id,
                 phoneColor: res.data.data.category.color
               },
             });
           } else {
             wx.showToast({
               title: res.data.msg,
               icon: 'loading',
               duration: 2000,
               mask: true
             });
           }
         }
       });
     }else{
       wx.showToast({
         title: '好像没网了...',
         icon:'loading',
         duration:2000,
         mask:true
       });
     }
   },
 });
}

/**故障列表**/
function faultList(e, id, type, title) {
  wx.getNetworkType({
    success: function(res) {
      wx.showLoading({
        title: '加载中...',
        mask:true
      });
      if(res.networkType != "none"){
        wx.request({
          method: "POST",
          url: config.service.faultList,
          data: {
            uid: wx.getStorageSync("loginInfo").uid,
            logintoken: wx.getStorageSync("loginInfo").token,
            category_id: id,
            error_type: type
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success(res) {
            console.log("订单列表:",res);
            wx.hideLoading();
            if (res.data.code == 1) {
              for (var i = 0; i < res.data.data.length; i++) {
                if(i > 0){
                  res.data.data[i].select = false;
                }else{
                  console.log(i);                 
                  res.data.data[i].select = true;   //   默认选中第一个              
                }
              }
              e.setData({
                Ofault: {
                  hintOfault: 'hint-Ofault',
                  title: title,
                  faultListData: res.data.data,
                  itemsEvent: "itemsEvent",
                  cancelEvent: "cancelEvent",
                  confirmEvent: "confirmEvent",
                  showComment: res.data.data[0].comment,
                  comment:res.data.comment
                }
              });
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'loading',
                duration: 2000,
                mask: true
              });
            }
          }
        });
      }else{
        wx.showToast({
          title: '好像没网了...',
          icon:'loading',
          duration:2000,
          mask:true
        });
      }
    },
  });
}